import axios from 'axios';
import { download } from '@/utils/file';

export interface issueRecipient {
  createBy: string;
  createDate: string;
  id: string;
  email: string;
  name: string;
}
export interface issuesData {
  id: string;
  title: string;
  projectId: string;
  state: number;
  createBy: string;
  receivers: string;
  createDate: string;
  message: string;
  file: string;
  issueRecipientList?: Array<issueRecipient>;
  [propsName: string]: any;
}

export interface issuesParams extends Partial<issuesData> {
  pageNo: number;
  pageSize: number;
}

export interface issuesListRes {
  list: issuesData[];
  total: number;
  message: string;
}

export interface issuesSave {
  projectId: string;
  fileIds: Array<string>;
  message: string;
  receivers: Array<string>;
  title: string;
}

export interface issuesStatus {
  issueId: string;
  status: string;
}

export interface FileInfo {
  createBy?: string;
  createDate?: string;
  deleteFlag?: number;
  description?: string;
  fileId?: string;
  fileToken?: string;
  folderId?: string;
  id?: string;
  isLocked?: boolean;
  name?: string;
  projectId?: string;
  size?: string;
  teamId?: string;
  type?: string;
  updateBy?: string;
  updateDate?: string;
  version?: string;
}

export function fileDownload(fileToekn: string) {
  return axios.get<string>('/sys-storage/download', {
    params: {
      f8s: fileToekn,
    },
    responseType: 'blob',
  });
}

// 查询问题列表-分页
export function queryissuesList(params: issuesParams) {
  return axios.get<issuesListRes>('/cde-collaboration/issue/list', {
    params,
  });
}

// 创建问题
export function addIssue(data: issuesData) {
  const param: issuesData = { ...data };
  return axios.post<issuesListRes>('/cde-collaboration/issue/save', param);
}

// 更新问题状态
export function updateStatus(data: issuesStatus) {
  const param: issuesStatus = { ...data };
  return axios.post('/cde-collaboration/issue/updatestatus', param);
}

// 下载
export async function issueFileDownload(fileInfo: FileInfo) {
  const res: any = await fileDownload(fileInfo.fileToken || '');
  download({ name: fileInfo.name || '' }, res.data);
}

export const getDirectoryFileInfo = (directory: any) => {
  let total = 0;
  let fileIDList: Array<string> = [];
  if (directory.children?.length) {
    directory.children.forEach((item: any) => {
      if (item.isFileOrFolder === 1) {
        total += 1;
        fileIDList.push(item.id);
      } else {
        total += getDirectoryFileInfo(item).total;
        fileIDList = fileIDList.concat(getDirectoryFileInfo(item).fileIDList);
      }
    });
  }
  return { total, fileIDList };
};
